using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Security.Claims; // Add this import for ClaimsPrincipal
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Authorization;
using RiceShop.Models;
using RiceShop.Services;

namespace RiceShop.Controllers
{

    [Route("api/[controller]")]
    [ApiController]
    public class AdminController : ControllerBase
    {
        private readonly IAdminService _adminService;  // 使用 IAdminService 接口

        public AdminController(IAdminService adminService)  // 使用依赖注入
        {
            _adminService = adminService;
        }

        /// <summary>
        /// 获取所有管理员。
        /// </summary>
        /// <returns>管理员列表。</returns>
        [HttpGet("list")]
        public ActionResult<IEnumerable<Admin>> GetAdmins(
            [FromQuery] string? search = null,
            [FromQuery] string sortBy = "adminName",
            [FromQuery] bool ascending = true,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 10)
        {
            var admins = _adminService.GetAdmins(search ?? "", sortBy, ascending, page, pageSize);
            int adminCount = _adminService.GetAdminsCount(search ?? "");

            // 使用静态方法创建 ApiResponse
            return Ok(ApiResponse<IEnumerable<Admin>>.Ok(admins, "获取管理员列表成功", adminCount));
        }

        /// <summary>
        /// 根据管理员ID获取管理员信息。
        /// </summary>
        /// <param name="id">管理员ID。</param>
        /// <returns>管理员信息。</returns>
        [HttpGet("detail/{id}")]
        public ActionResult<Admin> GetAdmin(long id)
        {
            var admin = _adminService.GetAdminById(id);
            if (admin == null)
            {
                return NotFound();
            }
            return Ok(admin);
        }

        /// <summary>
        /// 创建新管理员。
        /// </summary>
        /// <param name="admin">管理员信息。</param>
        /// <returns>创建的管理员信息。</returns>
        [HttpPost("create")]
        public async Task<ActionResult<Admin>> CreateAdmin([FromBody] Admin admin)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // 对密码进行哈希处理
            admin.adminPassword = BCrypt.Net.BCrypt.HashPassword("123456");

            var createdAdmin = await _adminService.CreateAdminAsync(admin);
            return CreatedAtAction(nameof(GetAdmin), new { id = createdAdmin.adminId }, createdAdmin);
        }

        /// <summary>
        /// 更新管理员信息。
        /// </summary>
        /// <param name="id">管理员ID。</param>
        /// <param name="admin">更新后的管理员信息。</param>
        /// <returns>操作结果。</returns>
        [HttpPut]
        [Route("update/{id}")]
        public async Task<IActionResult> UpdateAdmin(long id, [FromBody] Admin admin)
        {
            var adminInDb = _adminService.GetAdminById(id);

            if (adminInDb == null)
            {
                return NotFound();
            }

            adminInDb.adminNickName = admin.adminNickName;
            adminInDb.adminEmail = admin.adminEmail;
            adminInDb.adminPhone = admin.adminPhone;
            adminInDb.adminIp = admin.adminIp;
            adminInDb.adminName = admin.adminName;
            adminInDb.adminPassword = admin.adminPassword;
            adminInDb.adminStatus = admin.adminStatus;
            adminInDb.adminType = admin.adminType;
            adminInDb.adminUtime = DateTime.Now;

            // 更新其他属性...

            try
            {
                await _adminService.UpdateAdminAsync(adminInDb);
                return NoContent();
            }
            catch (DbUpdateException)
            {
                // 处理异常，例如记录日志
                return StatusCode(500, "An error occurred while updating the admin.");
            }


        }

        /// <summary>
        /// 删除管理员。
        /// </summary>
        /// <param name="id">管理员ID。</param>
        /// <returns>操作结果。</returns>
        [HttpDelete("{id}")]
        public IActionResult DeleteAdmin(long id)
        {
            var result = _adminService.DeleteAdmin(id);
            if (!result)
            {
                return NotFound();
            }
            return NoContent();
        }

        /// <summary>
        /// 获取所有管理员（示例方法）。
        /// </summary>
        /// <returns>管理员列表。</returns>
        [HttpGet("all")]
        public IEnumerable<Admin> GetAllAdmins()
        {
            // 从数据库中获取所有管理员
            return _adminService.GetAllAdmins();
        }

        /// <summary>
        /// 注册新管理员。
        /// </summary>
        /// <param name="admin">管理员信息。</param>
        /// <returns>创建的管理员信息。</returns>
        [HttpPost("register")]
        [AllowAnonymous]
        public async Task<ActionResult<Admin>> Register(Admin admin)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var createdAdmin = await _adminService.CreateAdminAsync(admin);
            return CreatedAtAction(nameof(GetAdmin), new { id = createdAdmin.adminId }, createdAdmin);
        }

        /// <summary>
        /// 获取当前管理员的个人信息。
        /// </summary>
        /// <returns>管理员信息。</returns>
        [HttpGet("profile")]
        public ActionResult<Admin> GetAdminProfile()
        {
            try
            {
                long adminId = GetAdminIdFromToken();
                var admin = _adminService.GetAdminById(adminId);
                if (admin == null)
                {
                    return NotFound(ApiResponse<Admin>.Error("Admin not found"));
                }
                return Ok(ApiResponse<Admin>.Ok(admin, "获取管理员信息成功"));
            }
            catch (UnauthorizedAccessException ex)
            {
                return Unauthorized(ApiResponse<Admin>.Error(ex.Message));
            }
        }

        /// <summary>
        /// 更新当前管理员的个人信息。
        /// </summary>
        /// <param name="admin">更新后的管理员信息。</param>
        /// <returns>操作结果。</returns>
        [HttpPut("profile")]
        public async Task<IActionResult> UpdateAdminProfile(Admin admin)
        {
            long adminId = GetAdminIdFromToken();
            if (adminId != admin.adminId)
            {
                return BadRequest("Admin ID mismatch.");
            }

            await _adminService.UpdateAdminAsync(admin);
            return NoContent();
        }

        /// <summary>
        /// 为管理员分配角色。
        /// </summary>
        /// <param name="model">角色分配模型，包含管理员ID和角色名称。</param>
        /// <returns>操作结果。</returns>
        [HttpPost("assignRole")]
        public IActionResult AssignRole([FromBody] AssignRoleModel model)
        {

            _adminService.AssignRoleToAdmin(model);

            return NoContent();
        }

        /// <summary>
        /// 获取管理员的角色列表。
        /// </summary>
        /// <param name="adminId">管理员ID。</param>
        /// <returns>角色列表。</returns>
        [HttpGet("roles")]
        public ActionResult<IEnumerable<long>> GetAdminRoles([FromQuery] long adminId)
        {

            var roles = _adminService.GetRolesByAdminId(adminId);
            return Ok(ApiResponse<IEnumerable<long>>.Ok(roles, "获取管理员角色列表成功"));
        }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="model">登录信息</param>
        /// <returns>登录结果，包含访问令牌和刷新令牌</returns>
        [HttpPost("login")]
        [AllowAnonymous]
        public ActionResult<ApiResponse<TokenResult>> Login([FromBody] LoginModel model)
        {
            var tokenResult = _adminService.AuthenticateAdminByAdminname(model.AdminName, model.Password);
            if (tokenResult == null)
            {
                return Unauthorized(ApiResponse<TokenResult>.Error("用户名或密码错误"));
            }

            return Ok(ApiResponse<TokenResult>.Ok(tokenResult, "登录成功"));
        }

        /// <summary>
        /// 刷新访问令牌
        /// </summary>
        /// <param name="request">包含刷新令牌的请求</param>
        /// <returns>新的令牌信息</returns>
        [HttpPost("refresh-token")]
        public ActionResult<ApiResponse<TokenResult>> RefreshToken([FromBody] RefreshTokenRequest request)
        {
            var tokenResult = _adminService.RefreshToken(request.RefreshToken);
            if (tokenResult == null)
            {
                return Unauthorized(ApiResponse<TokenResult>.Error("无效的刷新令牌"));
            }

            return Ok(ApiResponse<TokenResult>.Ok(tokenResult, "令牌刷新成功"));
        }

        /// <summary>
        /// 管理员注销
        /// </summary>
        /// <returns>操作结果</returns>
        [HttpPost("logout")]
        public ActionResult<ApiResponse<object>> Logout()
        {
            // 实现注销逻辑，例如使当前令牌失效
            return Ok(ApiResponse<object>.Ok(null, "注销成功"));
        }

        // 移除 Login 和 Logout 方法

        // Add this method to extract admin  ID from JWT token
        private long GetAdminIdFromToken()
        {
            // 确保管理员已认证
            if (!User.Identity?.IsAuthenticated ?? true)
            {
                throw new UnauthorizedAccessException("Admin not authenticated");
            }

            var adminIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
            if (adminIdClaim == null || string.IsNullOrEmpty(adminIdClaim.Value))
            {
                throw new UnauthorizedAccessException("Admin ID claim not found in token");
            }

            if (!long.TryParse(adminIdClaim.Value, out long adminId))
            {
                throw new UnauthorizedAccessException("Invalid admin ID format in token");
            }

            return adminId;
        }

        private bool AdminExists(long id)
        {
            return _adminService.AdminExists(id);
        }

        [HttpPut("updateNickname/{adminId}")]
        public IActionResult UpdateAdminNickname(long adminId, [FromBody] string newNickname)
        {
            var admin = _adminService.GetAdminById(adminId);
            if (admin != null)
            {
                admin.adminNickName = newNickname;
                _adminService.UpdateAdminAsync(admin).Wait(); // 确保更新操作被等待
                return Ok("Nickname updated successfully.");
            }
            return NotFound("Admin not found.");
        }
    }
}
